import { defineStore } from "pinia";
import { IProduct } from "~~/server/api/products";

const UseShoppingCartStore = defineStore("shopping_cart", {
  state: () => {
    return {
      products: [] as Array<IShopping_cart>,
    };
  },
  getters: {
    totalPrice(state) {
      const totalPrice = state.products.reduce((totalPrice, item) => {
        return totalPrice + item.price * item.quantity;
      }, 0);
      return totalPrice;
    },
  },
  actions: {
    AddProduct(product: IProduct) {
      // 如果存在 退出
      const res = this.products.find((item) => item.id == product.id);
      if (res) return;

      this.products.push({
        id: product.id,
        title: product.title,
        price: product.price,
        quantity: 0,
      });
    },
    IncProQuantity(id: number) {
      const product: IShopping_cart = this.products.find(
        (item) => item.id == id
      );
      product.quantity++;
    },
  },
});

export interface IShopping_cart extends Omit<IProduct, "inventory"> {
  quantity: number;
}
export { UseShoppingCartStore };
